<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
          >查询</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['output:cpmStart:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="type1"
          @click="handleEdit"
          v-hasPermi="['output:cpmStart:edit']"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="type1"
          @click="handleDelete"
          v-hasPermi="['output:cpmStart:remove']"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-circle-check"
          size="mini"
          :disabled="cpmStartList.length < 2"
          @click="consolidationOfDocuments"
          v-hasPermi="['output:cpmStart:consolidationOfDocuments']"
        >
          合并单据
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-circle-check"
          size="mini"
          :disabled="type1 || mxDate"
          @click="handleSubmit"
          v-hasPermi="['output:cpmStart:submit']"
        >
          提交
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport(1)"
          v-hasPermi="['output:cpmStart:export']"
        >
          导出头表
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport(2)"
          v-hasPermi="['output:cpmStart:export']"
        >
          导出子表
        </el-button>
      </el-col>
      <Tag type="dot" size="default" color="#0fac09">提交</Tag>
      <Tag type="dot" size="default" color="#bb0331">过账</Tag>
      <Tag type="dot" size="default" color="#0323af">审核</Tag>
      <Tag type="dot" size="default" color="rgb(195,39,174)">批准</Tag>
      <el-col :span="2.2" style="position: absolute; right: 35px; top: 0">
        <Page
          style="margin-right: 0px"
          :current="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          @on-change="pageChange"
          simple
        ></Page>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      highlight-current-row
      border
      stripe
      :height="tableH"
      v-loading="loading"
      :data="cpmStartList"
      @row-click="clickRow"
      :cell-style="iCellStyle"
      @selection-change="handleSelectionChange"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column label="#" width="40" type="index" align="center" />
      <el-table-column
        label="退货单号"
        :show-overflow-tooltip="true"
        width="135"
        align="center"
        prop="cpmDjbh"
      />
      <el-table-column
        label="退货日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="cpmCtrq"
        width="150"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.cpmCtrq, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="退货班组"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="cpmCsdm"
      ></el-table-column>
      <el-table-column
        label="仓库"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="cpmCkdm"
      >
        <template #default="scope">
          <dict-tag :options="allStorageOptions" :value="scope.row.cpmCkdm" />
        </template>
      </el-table-column>
      <el-table-column
        label="撤回原因"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="cpmNgdesc"
      />
      <el-table-column
        label="退货状态"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="cpmZtbz"
      >
        <template #default="scope">
          <dict-tag :options="cpmZtbzOptions" :value="scope.row.cpmZtbz" />
        </template>
      </el-table-column>
      <el-table-column
        label="建立人员"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="cpmJlry"
      />
      <el-table-column
        label="建立日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="cpmJlrq"
        width="150"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.cpmJlrq, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="审核人员"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="cpmShry"
      />
      <el-table-column
        label="审核日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="cpmShrq"
        width="150"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.cpmShrq, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="批准人员"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="cpmPzry"
      />
      <el-table-column
        label="批准日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="cpmPzrq"
        width="150"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.cpmPzrq, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="过账人员"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="cpmGzry"
      />
      <el-table-column
        label="过账日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="cpmGzrq"
        width="150"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.cpmGzrq, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        width="100"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            :disabled="scope.row.cpmTjflag == 1"
            @click="handleAddCpd(scope.row)"
            v-hasPermi="['output:cpdStart:add']"
          >
            添加
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="openChild"
      :fullscreen="true"
      :close-on-click-modal="false"
      append-to-body
    >
      <!-- 子项搜索条件框-->
      <el-form :model="queryChildParams" :inline="true">
        <el-row>
          <el-col :span="6">
            <el-form-item label="物料代码" prop="itmWldm">
              <el-input
                v-model="queryChildParams.itmWldm"
                placeholder="请输入物料代码"
                clearable
                size="small"
                @keyup.enter.native="serachChildrened"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则描述" prop="itmPmgg">
              <el-input
                v-model="queryChildParams.itmPmgg"
                placeholder="请输入规则描述"
                clearable
                size="small"
                @keyup.enter.native="serachChildrened"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item style="display: flex; justify-content: flex-end">
              <el-button type="primary" @click="serachChildrened"
                >查询</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!--子项数据框-->
      <el-form>
        <el-table
          highlight-current-row
          v-loading="loading"
          :data="serachAddList"
          border
          stripe
          :height="tableHNoChild"
          :header-cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column
            label="#"
            min-width="5%"
            type="index"
            align="center"
          />
          <el-table-column
            label="物料代码"
            min-width="20%"
            :show-overflow-tooltip="true"
            align="center"
            prop="cpdWldm"
          />
          <el-table-column
            label="规格描述"
            :show-overflow-tooltip="true"
            min-width="20%"
            prop="itmPmgg"
          />
          <el-table-column
            label="单位"
            min-width="10%"
            :show-overflow-tooltip="true"
            align="center"
            prop="itmDw"
          >
            <template #default="scope">
              <dict-tag :options="unitFlagOptions" :value="scope.row.itmDw" />
            </template>
          </el-table-column>
          <el-table-column
            label="存放位置"
            min-width="12%"
            align="center"
            prop="cpdCwdm"
          >
            <template #default="scope">
              <dict-tag :options="allCwOptions" :value="scope.row.cpdCwdm" />
            </template>
          </el-table-column>
          <el-table-column
            label="可用库存"
            min-width="10%"
            :show-overflow-tooltip="true"
            align="center"
            prop="kcmKykc"
          />
          <el-table-column
            label="需申请数"
            min-width="10%"
            align="center"
            prop="cpdSqsl"
          >
            <template #default="scope">
              <el-input-number
                size="mini"
                v-model="scope.row.cpdSqsl"
                :min="0"
                :max="scope.row.kcmKykc"
              ></el-input-number>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :page-size="queryChildParams.pageSize"
          :current-page.sync="queryChildParams.pageNum"
          @current-change="pageChangeChild"
          layout="total, prev, pager, next"
          :total="total2"
          style="text-align: right"
        ></el-pagination>
        <el-form-item
          style="margin-top: 25px; display: flex; justify-content: flex-end"
        >
          <el-button @click="openChild = false">取消</el-button>
          <el-button type="primary" @click="handAddChildren">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--明细-->
    <el-tabs v-model="activeTab">
      <el-tab-pane label="明细" name="first">
        <el-table
          border
          stripe
          :height="tableHAddChild"
          :data="cpdList"
          id="exportMx"
          :header-cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column label="#" type="index" align="center" fixed="left" />
          <el-table-column
            label="物料代码"
            :show-overflow-tooltip="true"
            width="135"
            align="center"
            prop="cpdWldm"
          />
          <el-table-column
            label="品名规格"
            :show-overflow-tooltip="true"
            prop="itmPmgg"
          />
          <el-table-column
            label="单位"
            :show-overflow-tooltip="true"
            width="80"
            align="center"
            prop="itmDw"
          >
            <template #default="scope">
              <dict-tag :options="unitFlagOptions" :value="scope.row.itmDw" />
            </template>
          </el-table-column>
          <el-table-column
            label="申请数量"
            :show-overflow-tooltip="true"
            width="100"
            align="center"
            prop="cpdSqsl"
          />
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="领料统计" name="second">
        <el-table border stripe :height="tableHAddChild" :data="cpdListTotal">
          <el-table-column
            label="物料代码"
            :show-overflow-tooltip="true"
            width="135"
            align="center"
            prop="cpdWldm"
          />
          <el-table-column
            label="品名规格"
            :show-overflow-tooltip="true"
            width="400"
            prop="itmPmgg"
          />
          <el-table-column
            label="单位"
            :show-overflow-tooltip="true"
            width="80"
            align="center"
            prop="itmDw"
          >
            <template #default="scope">
              <dict-tag :options="unitFlagOptions" :value="scope.row.itmDw" />
            </template>
          </el-table-column>
          <el-table-column
            label="申请数量"
            :show-overflow-tooltip="true"
            width="100"
            align="center"
            prop="cpdSqsl"
          />
          <el-table-column
            label="不良原因"
            :show-overflow-tooltip="true"
            align="center"
            prop="cpdBlyy"
          />
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="200"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                :disabled="type1"
                @click="handleDeleteCpd(scope.row)"
                v-hasPermi="['output:cpdStart:delete']"
              >
                删除
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                :disabled="type1"
                @click="handleEditCpd(scope.row)"
                v-hasPermi="['output:cpdStart:edit']"
              >
                填写不良原因
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 查询对话框   -->
    <el-dialog
      :title="title"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="680px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="70px"
      >
        <el-col :span="12">
          <el-form-item label="退货单号" prop="cpmDjbh">
            <el-input
              v-model="queryParams.cpmDjbh"
              placeholder="请输入退货单号"
              clearable
              style="width: 240px"
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开单日期">
            <el-date-picker
              v-model="daterangeCpmJlrq"
              :picker-options="pickerOptions"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              type="daterange"
              :clearable="false"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <RadioGroup v-model="queryParams.cpmZtbz">
              <Radio label="2" style="margin: 0px 30px">未审核</Radio>
              <Radio label="3" style="margin-right: 30px">已审核</Radio>
              <Radio label="1" align="right">全部</Radio>
            </RadioGroup>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="margin-top: 25px; display: flex; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>

    <!-- 添加或修改对外生产借料开单作业对话框 -->
    <el-dialog
      :title="title"
      v-model="blView"
      :close-on-click-modal="false"
      draggable
      width="680px"
      append-to-body
    >
      <el-form ref="form" :model="cpdForm" label-width="80px">
        <el-col :span="12">
          <el-form-item label="不良描述" prop="cpdBlyy">
            <el-input v-model="cpdForm.cpdBlyy" placeholder="请输入不良描述" />
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="blView = false">取 消</el-button>
        <el-button type="primary" @click="submitCpdForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改对外生产借料开单作业对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :close-on-click-modal="false"
      draggable
      width="480px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-col :span="24">
          <el-form-item label="成品不良退库单号" prop="cpmDjbh">
            <el-input
              v-model="form.cpmDjbh"
              disabled
              placeholder="请输入单号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="成品不良退库日期" prop="cpmCtrq">
            <el-date-picker
              clearable
              size="small"
              v-model="form.cpmCtrq"
              type="date"
              value-format="yyyy-MM-dd"
              :clearable="false"
              placeholder="选择成品不良退库日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="成品不良退库仓库" prop="cpmCkdm">
            <el-select v-model="form.cpmCkdm" placeholder="请选择仓库">
              <el-option
                v-for="item in storageOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCpmStart,
  getNeedData,
  delCpmStart,
  submitCpm,
  addCpmStart,
  editCpmStart,
  getCpmStartDetail,
  getCpmStart,
  exportCpm,
  exportCpd,
  addCpd,
  deleteCpmStartDetail,
  editCpd,
  consolidationOfDocuments,
} from "@/api/output/cpm";
import {
  getAll,
  getFinishedOrSemiFinishedProduct,
  getstorageType,
} from "@/api/repertory/Storage";

export default {
  name: "OutSourcing",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      cpmDjbhs: [],
      //选中的单据
      cpmMstrs: [],
      //选中的数据
      clickCpmList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      openSearch: false,
      //单位字典
      unitFlagOptions: [],
      storageOptions: [],
      allStorageOptions: [],
      activeTab: "second",
      tableHNoChild: 400,
      tableH: 250,
      tableHChild: 300,
      tableHAdd: 250,
      tableHAddChild: 300,
      //存放位置
      allCwOptions: [],
      //所有厂商
      allCsOptions: [],
      // 退货状态字典
      cpmZtbzOptions: [
        { dictValue: "1", dictLabel: "新增", listClass: "default" },
        { dictValue: "2", dictLabel: "审核", listClass: "default" },
        { dictValue: "3", dictLabel: "批准", listClass: "default" },
        { dictValue: "6", dictLabel: "过账", listClass: "default" },
      ],
      // 总条数
      total: 0,
      // 退货出库表格数据
      cpmStartList: [],
      //查询到可接收的物料
      needDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //不良原因填写显示框
      blView: false,
      rowData: null,
      id: null,
      type1: true,
      mxDate: true,
      cpdList: [],
      cpdListTotal: [],
      openChild: false,
      serachAddList: [],
      total2: 0,
      rules: {
        cpmCtrq: [
          { required: true, message: "退货日期不能为空", trigger: "blur" },
        ],
        cpmCkdm: [
          { required: true, message: "仓库代码不能为空", trigger: "change" },
        ],
        cpmCsdm: [
          { required: true, message: "班组不能为空", trigger: "change" },
        ],
      },
      // 建立日期时间范围
      daterangeCpmJlrq: [
        this.$moment().startOf("month").toDate(),
        this.$moment().add(100, "year").endOf("month").toDate(),
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        cpmDjbh: null,
        cpmWldm: null,
        cpmJlrq: null,
        itmPmgg: null,
        cpmZtbz: "2",
      },
      // 子项查询参数
      queryChildParams: {
        pageNum: 1,
        pageSize: 25,
        cjmDjbh: null,
        cpmCkdm: null,
        cpdWldm: null,
        itmPmgg: null,
      },
      // 表单参数
      form: {},
      cpdForm: {
        cpdWldm: null,
        cpdDjbh: null,
        cpdBlyy: null,
      },
      //日期初始化
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  created() {
    //单位
    this.getDicts("sys_unit").then((response) => {
      this.unitFlagOptions = response.data;
    });

    //有效仓库
    getFinishedOrSemiFinishedProduct().then((response) => {
      this.storageOptions = response.data;
      for (let item of this.storageOptions) {
        item.dictLabel = item.storageName;
        item.listClass = "default";
        item.dictValue = item.storageId + "";
      }
    });

    //所有仓库
    getAll().then((response) => {
      this.allStorageOptions = response.data;
      for (let item of this.allStorageOptions) {
        item.dictLabel = item.storageName;
        item.listClass = "default";
        item.dictValue = item.storageId + "";
      }
    });

    getAll().then((response) => {
      this.allCwOptions = response.data;
      for (let item2 of this.allCwOptions) {
        item2.dictLabel = item2.storageDefaultstorage;
        item2.listClass = "default";
        item2.dictValue = item2.storageId + "";
      }
    });

    this.getList();
  },
  methods: {
    /** 颜色事件 */
    iCellStyle: function ({ row, column, rowIndex, columnIndex }) {
      //提交
      if (row.cpmZtbz == "1" && row.cpmTjflag == "1") {
        return "color:#0fac09";
      }
      //过账
      else if (row.cpmZtbz == "2" && row.cpmTjflag == "1") {
        return "color:#bb0331";
      }
      //审核
      else if (row.cpmZtbz == "6" && row.cpmTjflag == "1") {
        return "color:#0323af";
      }
      //批准
      else if (row.cpmZtbz == "3" && row.cpmTjflag == "1") {
        return "color:rgb(195,39,174)";
      }
    },
    /** 查询退货出库列表 */
    getList(row) {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCpmJlrq && "" != this.daterangeCpmJlrq) {
        this.queryParams.params["beginCpmJlrq"] = this.moment(
          this.daterangeCpmJlrq[0]
        ).format("YYYY-MM-DD HH:mm:ss");
        this.queryParams.params["endCpmJlrq"] = this.moment(
          this.daterangeCpmJlrq[1]
        ).format("YYYY-MM-DD HH:mm:ss");
      }
      this.cpmStartList = [];
      listCpmStart(this.queryParams).then((response) => {
        this.cpmStartList = response.rows;
        this.total = response.total;
        this.loading = false;
        if (row != null) {
          this.clickRow(row);
        } else if (this.cpmStartList != null && this.cpmStartList.length > 0) {
          this.clickRow(this.cpmStartList[0]);
        } else {
          this.type1 = true;
        }
      });
    },

    // 获取明细
    getRowDetList(order) {
      getCpmStartDetail(order).then((response) => {
        this.cpdList = response.data.list;
        this.cpdListTotal = response.data.total;
        this.mxDate = this.cpdList.length > 0 ? false : true;
      });
    },

    clickRow(row) {
      // //获得选中的详细数据
      this.rowData = row;
      // //获得当前单据的状态
      this.id = row.cpmId;
      this.type1 = !(row != null && row.cpmZtbz == "1" && row.cpmTjflag == "0");
      //获得选中的详细数据
      this.getRowDetList(row.cpmDjbh);
    },

    pageChange(page) {
      this.queryParams.pageNum = page;
      this.getList();
    },

    pageChangeChild(page) {
      this.queryChildParams.pageNum = page;
      this.serachChildrened();
    },

    //删除明细
    handleDeleteCpd(row) {
      deleteCpmStartDetail(this.rowData.cpmDjbh, row.cpdWldm).then((res) => {
        this.msgSuccess("删除成功");
        this.clickRow(this.rowData);
      });
    },

    handleEditCpd(row) {
      this.cpdForm.cpdBlyy = null;
      this.cpdForm.cpdDjbh = this.rowData.cpmDjbh;
      this.cpdForm.cpdWldm = row.cpdWldm;
      this.title = "填写不良原因";
      this.blView = true;
    },

    submitCpdForm() {
      if (this.cpdForm.cpdBlyy) {
        editCpd(this.cpdForm).then((res) => {
          this.msgSuccess("修改成功");
          this.blView = false;
          this.getList(this.rowData);
        });
      } else {
        this.msgError("请填写原因");
      }
    },

    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.cpmCtrq = this.$moment(this.form.cpmCtrq).format();
          if (this.form.cpmId != null) {
            editCpmStart(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList(this.rowData);
            });
          } else {
            addCpmStart(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openSearch = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        cpmId: null,
        cpmDjbh: null,
        cpmCtrq: null,
        cpmCsdm: null,
        cpmCkdm: null,
        cpmNgdesc: null,
        cpmTjflag: null,
        cpmZtbz: null,
        cpmJlry: null,
        cpmJlrq: null,
        cpmShry: null,
        cpmShrq: null,
        cpmPzry: null,
        cpmPzrq: null,
        cpmGzry: null,
        cpmGzrq: null,
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.cpmStartList = [];
      this.getList();
      this.openSearch = false;
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCpmJlrq = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.cpmDjbhs = selection.map((item) => item.cpmDjbh);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.cpmMstrs = selection;
    },

    handleAddCpd(row) {
      this.reset();
      this.queryChildParams.cpmDjbh = row.cpmDjbh;
      this.queryChildParams.cpmCkdm = row.cpmCkdm;
      this.queryChildParams.pageNum = 1;
      getNeedData(this.queryChildParams).then((response) => {
        this.serachAddList = [];
        this.serachAddList = response.rows;
        this.total2 = response.total;
      });
      this.openChild = true;
    },

    //搜索需要添加的内容
    serachChildrened() {
      this.serachAddList = [];
      getNeedData(this.queryChildParams).then((response) => {
        this.serachAddList = response.rows;
        this.total2 = response.total;
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.form.cpmCtrq = new Date();
      this.title = "添加成品不良退库开单作业";
    },

    //修改
    handleEdit(row) {
      this.reset();
      const cpmId = row.cjmId || this.rowData.cpmId;
      getCpmStart(cpmId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改成品出库开单作业";
      });
    },
    /**
     *查询需要添加的数据
     */
    searchNeedData() {
      this.queryChildParams.pageNum = 1;
      this.needDataList = [];
      getNeedData(this.queryChildParams).then((res) => {
        this.needDataList = [];
        this.needDataList = this.needDataList.concat(res.rows);
        this.total2 = res.total;
      });
    },
    load2() {
      if (
        this.queryChildParams.pageNum <
        Math.ceil(this.total2 / this.queryChildParams.pageSize)
      ) {
        this.queryChildParams.pageSize = 40;
        this.queryChildParams.pageNum++;
        getNeedData(this.queryChildParams).then((res) => {
          this.needDataList = this.needDataList.concat(res.rows);
          this.total2 = res.total;
        });
      }
      return 0;
    },
    //检验状态
    check_state() {
      if (this.rowData.cpmZtbz != 1 || this.rowData.cpmTjflag != 0) return true;
      return false;
    },
    //单据提交
    handleSubmit() {
      if (this.check_state()) {
        this.msgError("选中的单据不是开单状态,无法进行提交");
      } else {
        submitCpm(this.rowData.cpmDjbh)
          .then((res) => {
            this.msgSuccess("提交成功");
            this.getList();
          })
          .catch(() => {
            this.msgError("提交失败");
          });
      }
    },
    handleSearch() {
      this.reset();
      this.title = "查询退货出库";
      this.openSearch = true;
    },
    changValue(row) {
      if (row.cpdSqsl > row.kcmKysl) {
        this.msgError("不允许超过可用库存");
        row.cpdSqsl = row.kcmKysl;
      }
    },
    handAddChildren() {
      const datas = this.serachAddList.filter((a) => {
        return !!a.cpdSqsl;
      });
      if (datas.length < 1) {
        this.msgError("请输入需要添加的物料~");
        return;
      }
      addCpd(datas)
        .then((response) => {
          this.msgSuccess("添加成功~");
          this.queryChildParams.pageNum = 1;
          this.serachAddList = [];
          this.serachChildrened();
          this.getRowDetList(this.queryChildParams.cpmDjbh);
        })
        .catch(() => {
          this.msgError("添加失败~");
        });
    },
    /** 添加按钮 */
    addCpm() {
      const datas = this.needDataList.filter((a) => {
        return !!a.cpmCksl && a.cpmCksl > 0;
      });
      if (datas.length < 1) {
        this.msgError("请勾选需要添加的物料~");
        return;
      }
      if (datas.some((o) => !o.cpmThyy)) {
        this.msgError("请填写退货原因后再提交！");
        return;
      }
      addCpd(datas)
        .then((res) => {
          this.msgSuccess("添加成功~");
          this.searchNeedData();
          this.getList();
        })
        .catch(() => {
          this.msgError("添加失败~");
        });
    },
    /** 删除按钮操作 */
    handleDelete() {
      if (this.check_state()) {
        this.msgError("选择的单据不是开单状态,无法删除");
      } else {
        const cpmDjbhss = this.rowData.cpmDjbh;
        this.$confirm('是否确认删除退货出库单号:"' + cpmDjbhss + '"?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return delCpmStart(cpmDjbhss);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(() => {});
      }
    },
    /** 导出按钮操作 */
    handleExport(index) {
      if (index === 1) {
        exportCpm(this.queryParams)
          .then((response) => {
            this.download(response.msg);
            this.exportLoading = false;
          })
          .catch(() => {});
      } else {
        this.queryParams.cpmDjbh = this.rowData.cpmDjbh;
        exportCpd(this.queryParams)
          .then((response) => {
            this.download(response.msg);
            this.exportLoading = false;
          })
          .catch(() => {});
      }
    },
    consolidationOfDocuments() {
      this.$confirm("请确认是否合并单据", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then((res) => {
        consolidationOfDocuments().then((res) => {
          this.msgSuccess("合并成功");
          this.getList();
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.inputName > .el-input__inner {
  height: 20px;
  line-height: 20px;
}
</style>
